import TYPE from "../type";

function countTotal(state){
    var total = 0;
    state.list.forEach(item=>{
       if(item.isCheck){
          total+=item.num*item.price
       }
    })
    state.total = total;
}


function cartReducer(state={list:[],total:0,isAllCheck:false},action){
    state = JSON.parse(JSON.stringify(state));
  
    switch(action.type){
   	    case TYPE.GET_CART:
   	        state.list = action.data;
            return state;

        case TYPE.ADD_CART_ITEM: 
             state.list = [{
                id:new Date().getTime(),
                img:"",
                name:"商品名称"+parseInt(Math.random()*10000),
                price:Math.random()*1000,
                isCheck:false,
                num:1
             },...state.list];
             return state;   
        
        case TYPE.DEL_CART_ITEM: 
            state.list = state.list.filter(item=>{
                 return item.id !== action.id
            })
            state.isAllCheck = state.list.every(item=>{
                 return item.isCheck
            })
            countTotal(state);
            return state;
        
        case TYPE.CHECK_CART_ITEM: 
             state.list.forEach(item=>{
                if(item.id === action.id){
                    item.isCheck = !item.isCheck;
                }
             })
             state.isAllCheck = state.list.every(item=>{
                 return item.isCheck
             })
             countTotal(state);
             return state;
        
        case TYPE.ADD_ITEM_NUM:
             state.list.forEach(item=>{
                 if(item.id === action.id){
                    item.num ++;
                 }
             })
             countTotal(state);
             return state;
        
        case TYPE.SUB_ITEM_NUM:
             state.list.forEach(item=>{
                if(item.id === action.id){
                    if(item.num!==1){
                      item.num --;
                    }
                }
             })
             countTotal(state); 
             return state;
        
        case TYPE.ALLCHECK_ITEM:
             state.isAllCheck = !state.isAllCheck;
             state.list.forEach(item=>{
                 item.isCheck = state.isAllCheck;
             })
             countTotal(state);
             return state;

        case TYPE.DEL_bY_QUERY:
             state.list = state.list.filter(item=>{
                 return item.isCheck==false;
             })
             countTotal(state);
             return state;
        
        default:
            return state;
    }

}


export default cartReducer;